package controller.event;

import DateTools.DateUtil;
import domain.entity.base.UserInfo;
import domain.entity.event.EventImgInfo;
import domain.entity.event.EventMessageInfo;
import domain.entity.event.TunnelEventInfo;
import domain.service.base.UserInfoService;
import domain.service.event.EventImgInfoService;
import domain.service.event.EventMessageInfoService;
import domain.service.event.OperatorInfoService;
import domain.service.event.TunnelEventInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import util.ImageUploadUtil;
import util.WebContextUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by bowen on 2017-08-18.
 */
@Controller
public class TunnelEventController {

    private static final Logger logger = LoggerFactory.getLogger(TunnelEventController.class);

    private String userId = "s513284660";

    @Autowired
    private TunnelEventInfoService infoService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private OperatorInfoService operatorInfoService;
    @Autowired
    private EventImgInfoService eventImgInfoService;
    @Autowired
    private EventMessageInfoService messageInfoService;


    @RequestMapping(value = "/upload_img", method = RequestMethod.POST)
    @ResponseBody
    public String getWeJsTicket(HttpServletRequest request, HttpServletResponse response, String imgData) {
        try {
            response.setHeader("Access-Control-Allow-Origin", "*");
            String imgType = "jpg";
            String filePath = request.getSession().getServletContext().getRealPath("/upload/");
            String fileName = (Math.random() * 10000) + "_." + imgType;
            filePath = filePath + "/" + fileName;
            ImageUploadUtil.GenerateImage(filePath, imgType, imgData);
            return "/upload/" + fileName;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 創建事件上報
     *
     * @param entity
     * @return
     */
    @RequestMapping(value = "addEvent", method = RequestMethod.POST)
    @ResponseBody
    public String addEvent(HttpServletRequest request, HttpServletResponse response, TunnelEventInfo entity) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        try {
            String filePath = request.getSession().getServletContext().getRealPath("/");
            String userId = WebContextUtil.getCurrentUser().getUserid();
            entity.setEventUser(userId);
            entity.setCreateUser(userId);
            infoService.create(entity, filePath);
            return "保存成功！";
        } catch (Exception e) {
            e.printStackTrace();
            return "保存失败！";
        }
    }

    /**
     * 我发起的事件
     *
     * @return
     */
    @RequestMapping("getMyCreateEvents")
    @ResponseBody
    public Map<String, Object> getMyCreateEvents(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        logger.info("+++++++++++++++++getMyCreateEvents+++++++++++++++++++++++++++++++++++++++++++++++++");
        String userId = WebContextUtil.getCurrentUser().getUserid();
        logger.info("+++++++++++++++++getMyCreateEvents+++++++++++++++++++" + userId + "++++++++++++++++++++++++++++++");

        Map<String, Object> dataMap = new HashMap<String, Object>();
        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
        List<TunnelEventInfo> list = infoService.getMyCreateEvents(userId);
        int countNo = 0;
        for (TunnelEventInfo eventInfo : list) {
            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("address", eventInfo.getAddress());
            resultMap.put("eventRemark", eventInfo.getNote());
            resultMap.put("time", DateUtil.DateToString(eventInfo.getEventDate(), "yyyy-MM-dd HH:mm:ss"));
            resultMap.put("eventId", eventInfo.getEventId());
            String user = "";
            List<Map<String, Object>> operatorList = operatorInfoService.getOperatorByEventId(eventInfo.getEventId(), eventInfo.getEventId());
            for (Map<String, Object> operatorMap : operatorList) {
                user += operatorMap.get("name") + ",";
            }
            if (user.equals("")) {
                resultMap.put("user", "@All");
            } else {
                resultMap.put("user", "@" + user.substring(0, user.length() - 1));
            }
            List<EventImgInfo> imgList = eventImgInfoService.getImgsByEventId(eventInfo.getId());
            resultMap.put("imgList", imgList);
            int total = infoService.getTotalEvent(eventInfo.getEventId());
            resultMap.put("total", total);
            int new_total = messageInfoService.getTotalUnread(eventInfo.getEventId(), userId);
            countNo = countNo + new_total;
            resultMap.put("new", new_total);
            resultList.add(resultMap);
        }
        //我发起的未读数
        int myUnread = messageInfoService.getMyTotalUnread(userId);
        //@我的未读数
        int atUnread = messageInfoService.getAtTotalUnread(userId);
        //公共未读数
        int publicUnread = messageInfoService.getPublicTotalUnread(userId);

        dataMap.put("myUnread", myUnread);
        dataMap.put("atUnread", atUnread);
        dataMap.put("publicUnread", publicUnread);
        dataMap.put("unread", countNo);
        dataMap.put("data", resultList);
        dataMap.put("total", resultList.size());
        return dataMap;
    }

    /**
     * @return
     * @我的事件
     */
    @RequestMapping("getAtEvents")
    @ResponseBody
    public Map<String, Object> getAtEvents(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        String userId = WebContextUtil.getCurrentUser().getUserid();

        Map<String, Object> dataMap = new HashMap<String, Object>();
        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
        List<TunnelEventInfo> list = infoService.getAtEvents(userId);
        int countNo = 0;
        for (TunnelEventInfo eventInfo : list) {
            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("address", eventInfo.getAddress());
            resultMap.put("eventRemark", eventInfo.getNote());
            resultMap.put("time", DateUtil.DateToString(eventInfo.getEventDate(), "yyyy-MM-dd HH:mm:ss"));
            resultMap.put("eventId", eventInfo.getEventId());
            UserInfo userInfo = userInfoService.getUserInfoById(eventInfo.getEventUser());
            String user = "";
            List<Map<String, Object>> operatorList = operatorInfoService.getOperatorByEventId(eventInfo.getEventId(), eventInfo.getEventId());
            for (Map<String, Object> operatorMap : operatorList) {
                user += operatorMap.get("name") + ",";
            }
            if (user.equals("")) {
                resultMap.put("user", "@All");
            } else {
                resultMap.put("user", "@" + user.substring(0, user.length() - 1));
            }
            List<EventImgInfo> imgList = eventImgInfoService.getImgsByEventId(eventInfo.getId());
            resultMap.put("imgList", imgList);
            int total = infoService.getTotalEvent(eventInfo.getEventId());
            resultMap.put("total", total);
            int new_total = messageInfoService.getTotalUnread(eventInfo.getEventId(), userId);
            countNo = countNo + new_total;
            resultMap.put("new", new_total);
            resultList.add(resultMap);
        }
        //我发起的未读数
        int myUnread = messageInfoService.getMyTotalUnread(userId);
        //@我的未读数
        int atUnread = messageInfoService.getAtTotalUnread(userId);
        //公共未读数
        int publicUnread = messageInfoService.getPublicTotalUnread(userId);

        dataMap.put("myUnread", myUnread);
        dataMap.put("atUnread", atUnread);
        dataMap.put("publicUnread", publicUnread);
        dataMap.put("unread", countNo);
        dataMap.put("data", resultList);
        dataMap.put("total", resultList.size());
        return dataMap;
    }

    /**
     * 公共事件
     *
     * @param
     * @return
     */
    @RequestMapping("getPublicEvents")
    @ResponseBody
    public Map<String, Object> getPublicEvents(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> dataMap = new HashMap<String, Object>();
        logger.info("+++++++++++++++++getPublicEvents+++++++++++++++++++++++++++++++++++++++++++");
        String userId = WebContextUtil.getCurrentUser().getUserid();
        logger.info("+++++++++++++++++getPublicEvents++++++++++++++++++++" + userId + "+++++++++++++++++++++++");
        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
        List<TunnelEventInfo> list = infoService.getPublicEvents(userId);
        int countNo = 0;
        for (TunnelEventInfo eventInfo : list) {
            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("address", eventInfo.getAddress());
            resultMap.put("eventRemark", eventInfo.getNote());
            resultMap.put("time", DateUtil.DateToString(eventInfo.getEventDate(), "yyyy-MM-dd HH:mm:ss"));
            resultMap.put("eventId", eventInfo.getEventId());
            List<EventImgInfo> imgList = eventImgInfoService.getImgsByEventId(eventInfo.getId());
            resultMap.put("imgList", imgList);
            int total = infoService.getTotalEvent(eventInfo.getEventId());
            resultMap.put("total", total);
            Map<String, Object> userMap = operatorInfoService.getEventUserByEventId(eventInfo.getEventId());
            if (userMap != null) {
                resultMap.put("user", userMap.get("name").toString());
            }
            int new_total = messageInfoService.getTotalUnread(eventInfo.getEventId(), userId);
            countNo = countNo + new_total;
            resultMap.put("new", new_total);
            resultList.add(resultMap);
        }
        //我发起的未读数
        int myUnread = messageInfoService.getMyTotalUnread(userId);
        //@我的未读数
        int atUnread = messageInfoService.getAtTotalUnread(userId);
        //公共未读数
        int publicUnread = messageInfoService.getPublicTotalUnread(userId);
        dataMap.put("myUnread", myUnread);
        dataMap.put("atUnread", atUnread);
        dataMap.put("publicUnread", publicUnread);
        dataMap.put("unread", countNo);
        dataMap.put("data", resultList);
        dataMap.put("total", resultList.size());

        return dataMap;
    }

    /**
     * 根据事件ID读取明细
     *
     * @param
     * @return
     */
    @RequestMapping("getDetailByEventId")
    @ResponseBody
    public List<TunnelEventInfo> getDetailByEventId(HttpServletResponse response, long eventId) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        logger.info("+++++++++++++++++getDetailByEventId+++++++++++++++++++++++++++++++++++++++++++");
        String userId = WebContextUtil.getCurrentUser().getUserid();
        logger.info("+++++++++++++++++getDetailByEventId++++++++++++" + userId + "+++++++++++++++++++++++++++++++");

        //事件本身做已读记录
        EventMessageInfo messageInfo = new EventMessageInfo();
        messageInfo.setEventId(eventId);
        messageInfo.setRevertId(eventId);
        messageInfo.setUserId(userId);
        messageInfoService.create(messageInfo);
        List<TunnelEventInfo> eventInfos = infoService.getDetailByEventId(eventId, userId);
        if (eventInfos != null && eventInfos.size() > 0) {
            TunnelEventInfo info = eventInfos.get(0);
            EventMessageInfo message = new EventMessageInfo();
            message.setEventId(info.getEventId());
            message.setRevertId(info.getId());
            message.setUserId(userId);
            messageInfoService.create(message);
        }
        return eventInfos;
    }

    /**
     * 創建事件上報
     *
     * @param revertId
     * @return
     */
    @RequestMapping(value = "addEventMessage", method = RequestMethod.POST)
    @ResponseBody
    public String addEventMessage(HttpServletResponse response, long revertId) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        String userId = WebContextUtil.getCurrentUser().getUserid();
        try {
            EventMessageInfo messageInfo = new EventMessageInfo();
            TunnelEventInfo eventInfo = infoService.getEventById(revertId);
            messageInfo.setEventId(eventInfo.getEventId());
            messageInfo.setRevertId(revertId);
            messageInfo.setUserId(userId);
            messageInfoService.create(messageInfo);
            return "保存成功！";
        } catch (Exception e) {
            e.printStackTrace();
            return "保存失败！";
        }
    }

}
